package com.dhcy.mqtt.autocode;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//自动生成代码的主类
@Slf4j
public class AutoCodeMain {

    AutoCodePar autoCodePar = new AutoCodePar();

    String packageName = getPackageName();

    String name = StrUtil.upperFirst(autoCodePar.getMainName());

    String mainName = autoCodePar.getMainName();

    public  AutoCodeMain(){

    }


    public static void main(String[] args) {
        AutoCodeMain autoCodeMain = new AutoCodeMain();
        FileContent fileContent = autoCodeMain.getAllCol();
        autoCodeMain.createModelAndPar(fileContent);
        autoCodeMain.createDao();
        autoCodeMain.generateInterface(fileContent);
        autoCodeMain.createController();
        autoCodeMain.createListHtml(fileContent);
        autoCodeMain.createAddHtml(fileContent);
        //  log.error(fileContent.getListFileString().toString());
        // log.error(fileContent.getSearchTjString().toString());
        // log.error(fileContent.getAddFileString().toString());

        //log.error(autoCodeMain.getResourcesPath());

    }


    //创建list页面
    private void createListHtml(FileContent fileContent) {
        StringBuilder listHtml = new StringBuilder();

        listHtml.append("<!DOCTYPE html>\n" +
                "<html xmlns:th=\"http://www.thymeleaf.org\" lang=\"zh\">\n" +
                "<head lang=\"en\">\n" +
                "    <th:block th:include=\"include :: header('首页')\" />\n" +
                "    <th:block th:include=\"include :: headertable\" />\n" +
                "</head>" +
                "<body>\n" +
                "<div class=\"panel panel-success\">\n" +
                "    <div class=\"panel-heading\">\n" +
                "        <h3 class=\"panel-title\">搜索条件</h3>\n" +
                "    </div>\n" +
                "    <div class=\"panel-body\">\n" +
                "\n" +
                "        <form class=\"layui-form layui-col-space5\">\n");
        listHtml.append(fileContent.getSearchTjString());
        listHtml.append("            <div class=\"layui-inline layui-show-xs-block\">\n" +
                "                <button class=\"layui-btn\" lay-submit=\"\" lay-filter=\"sreach\"><i class=\"layui-icon\">&#xe615;</i></button>\n" +
                "            </div>\n" +
                "        </form>\n" +
                "    </div>\n" +
                "</div>\n" +
                "\n" +
                "<div id=\"toolbar\">\n" +
                "    <button id=\"addAuthRole\" class=\"layui-btn\">+ 添加</button>\n" +
                "</div>\n" +
                "\n" +
                "<table id=\"dataTable\" lay-filter=\"dataTable\"></table>\n" +
                "\n" +
                "\n" +
                "<th:block th:include=\"include :: footer\" />\n" +
                "<th:block th:include=\"include :: footertable\" />\n" +
                "<script>\n" +
                "    layui.use(['table','form'], function () {\n" +
                "        var table = layui.table;\n" +
                "        var form=layui.form;\n" +
                "        form.on('submit(sreach)', function(data){\n" +
                "            config.tableQuery(\"dataTable\",data.field)\n" +
                "            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。\n" +
                "        });\n" +
                "\n" +
                "        function operateFormatter(value, row, index) {\n" +
                "            var operateHtml = new Array();\n" +
                "            operateHtml.push('<button data-method=\"confirmTrans\" class=\"layui-btn layui-btn-sm\" id=\"edit\" >编辑</button>');\n" +
                "            operateHtml.push('<button class=\"layui-btn layui-btn-sm layui-btn-danger\" id=\"delete\" >删除</button>');\n" +
                "            return operateHtml.join('');\n" +
                "        }\n" +
                "\n" +
                "        var operateEvents = {\n" +
                "            'click #edit': function (e, value, row, index) {\n" +
                "                json = row;\n" +
                "                config.openPageLayer(\"编辑\", \"" + autoCodePar.getHtmlFold() + "/add" + name + "\", ['500px', '400px'],\"\",false);\n" +
                "            },\n" +
                "            'click #delete': function (e, value, row, index) {\n" +
                "                json = row;\n" +
                "                config.openConfirmLayer(\"确定删除吗？\",\"/" + autoCodePar.getControllerPre() + "/" + mainName + "Del.json\",{\"id\":row.id},function (data) {\n" +
                "\nconfig.tableRefresh();\n" +
                "                })\n" +
                "            },\n" +
                "        };\n" +
                "\n" +
                "        config.initTable(\"#dataTable\", \"/" + autoCodePar.getControllerPre() + "/" + mainName + "List.json\", [ //表头\n");
        listHtml.append(fileContent.getListFileString());
        listHtml.append("                , {title: '操作', events: operateEvents, formatter: operateFormatter}");
        listHtml.append("            ]\n" +
                "            , {});\n" +
                "\n" +
                "        $(document).on('click', '#addAuthRole', function () {\n" +
                "            json={};\n" +
                "            config.openPageLayer(\"添加用户\", '" + autoCodePar.getHtmlFold() + "/add" + name + "', ['500px', '400px'],\"\",false);\n" +
                "        })\n" +
                "    })\n" +
                "</script>\n" +
                "\n" +
                "</body>\n" +
                "</html>");
        String fileName = getResourcesPath() + "templates/" + autoCodePar.getHtmlFold() + "/" + mainName + "List.html";
        writeXmlFile(listHtml.toString(), fileName);
    }

    private void createAddHtml(FileContent fileContent) {
        StringBuilder addHtml = new StringBuilder();
        addHtml.append("<!DOCTYPE html>\n" +
                "<html xmlns:th=\"http://www.thymeleaf.org\" lang=\"zh\">\n" +
                "<head lang=\"en\">\n" +
                "    <th:block th:include=\"include :: header('添加角色')\"/>\n" +
                "</head>" +
                "<body>\n" +
                "<form class=\"layui-form\" style=\"padding: 10px\" lay-filter=\"form\">\n");
        addHtml.append(fileContent.getAddFileString());
        addHtml.append("    <input type=\"hidden\" id=\"id\" name=\"id\">\n" +
                "    </div>\n" +
                "    <div style=\"display: none\">\n" +
                "        <button class=\"layui-btn\" lay-submit lay-filter=\"*\" id=\"submit\">立即提交</button>\n" +
                "    </div>\n" +
                "</form>\n" +
                "</body>\n" +
                "<th:block th:include=\"include :: footer\"/>\n" +
                "<script type=\"text/javascript\">\n" +
                "\n" +
                "    //从父层获取值，json是父层的全局js变量。eval是将该string类型的json串变为标准的json串\n" +
                "    layui.use(['form'], function () {\n" +
                "        var form = layui.form;\n" +
                "            if (parent.json) {\n" +
                "                var parent_json = parent.json;\n" +
                "                form.val(\"form\", {\n");
        addHtml.append(fileContent.getAddInitString());
        addHtml.append("                })\n" +
                "            }\n" +
                "            form.render(\"select\");                                // 刷性select，显示出数据\n" +
                "        form.on('submit(*)', function (data) {\n" +
                "            config.commPost(\"/" + autoCodePar.getControllerPre() + "/" + mainName + "Add.json\", data.field, function (data, info) {\n" +
                "                parent.config.tableRefresh();\n" +
                "                parent.config.closeLayer(info);\n" +
                "            })\n" +
                "            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。\n" +
                "        });\n" +
                "\n" +
                "    })\n" +
                "\n" +
                "    function ApplicationSave() {\n" +
                "        document.getElementById(\"submit\").click();\n" +
                "    }\n" +
                "</script>\n" +
                "</html>\n" +
                "\n");
        String fileName = getResourcesPath() + "templates/" + autoCodePar.getHtmlFold() + "/add" + name + ".html";
        writeXmlFile(addHtml.toString(), fileName);
    }


    //先创建model
    private void createModelAndPar(FileContent fileContent) {

        //String name = StrUtil.upperFirst(autoCodePar.getMainName());
        String fileName = name;
        String fold = "model";
        //生成model
        StrBuilder contentString = new StrBuilder("package " + getPackageName() + ".model; \n\n\n\n" +
                "import com.baomidou.mybatisplus.annotation.IdType;\n" +
                "import com.baomidou.mybatisplus.annotation.TableId;\n" +
                "import lombok.Data;\n" +
                "import io.swagger.annotations.ApiModel;\n" +
                "import io.swagger.annotations.ApiModelProperty;\n");
        contentString.append(fileContent.getImportString());
        contentString.append("\n\n\n");
        contentString.append("@Data\n" +
                "@ApiModel(value=\""+autoCodePar.getDesc()+"实体类\",reference =\""+autoCodePar.getDesc()+"实体类\" )\n" +
                "public class " + fileName + " {\n");
        contentString.append(fileContent.getContentString());
        contentString.append("\n}");

        //getFileContent(fold, fileName+ ".java");
        writeToFile(contentString.toString(), fold, fileName + ".java");


        //生成listPar
        fileName = name + "ListPar";
        fold = "par/ht";
        contentString.reset();
        contentString.append("package " + getPackageName() + ".par.ht; \n\n\n\n" +
                "import lombok.Data;\n" +
                "import io.swagger.annotations.ApiModel;\n" +
                "import io.swagger.annotations.ApiModelProperty;\n");
        contentString.append("\n\n\n");
        contentString.append("@Data\n" +
                "@ApiModel(value=\""+autoCodePar.getDesc()+"查询条件\",reference =\""+autoCodePar.getDesc()+"查询条件\" )\n" +
                "public class " + fileName + "  extends PagePar {\n");
        contentString.append(fileContent.getParListString());
        contentString.append("\n}");
        log.error(contentString.toString());

        //  getFileContent(fold, fileName);
        writeToFile(contentString.toString(), fold, fileName + ".java");

        //生成AddPar
        fileName = name + "AddPar";
        contentString.reset();
        contentString.append("package " + getPackageName() + ".par.ht; \n\n\n\n" +
                "import lombok.Data;\n" +
                "import javax.validation.constraints.NotBlank; \n" +
                "import io.swagger.annotations.ApiModel;\n" +
                "import io.swagger.annotations.ApiModelProperty;\n");
        contentString.append("\n\n\n");
        contentString.append("@Data\n" +
                "@ApiModel(value=\""+autoCodePar.getDesc()+"新增修改\",reference =\""+autoCodePar.getDesc()+"新增修改\" )\n" +
                "public class " + fileName + " {\n");
        contentString.append(fileContent.getAddParString());
        contentString.append("\n}");
        log.error(contentString.toString());

        // getFileContent(fold, fileName+ ".java");
        writeToFile(contentString.toString(), fold, fileName + ".java");

        //生成result
        produceResult(fileContent, contentString);
    }

    //凭借result
    private void produceResult(FileContent fileContent, StrBuilder contentString) {
        String fileName;
        String fold;
        fileName = name + "Result";
        fold = "result/ht";
        contentString.reset();
        contentString.append("package " + getPackageName() + ".result.ht; \n\n\n\n" +
                "import lombok.Data;\n");
        contentString.append(fileContent.getImportString());
        contentString.append("\n\n\n");
        contentString.append("@Data\n" +
                "public class " + fileName + " {\n");
        contentString.append(fileContent.getResultString());
        contentString.append("\n}");
        writeToFile(contentString.toString(), fold, fileName + ".java");
    }

    //生成dao和mapper
    private void createDao() {
        String content = "package " + packageName + ".dao;\n" +
                "\n" +
                "import com.baomidou.mybatisplus.core.mapper.BaseMapper;\n" +
                "import " + packageName + ".model." + name + ";\n" +
                "import org.apache.ibatis.annotations.Mapper;\n" +
                "\n" +
                "@Mapper\n" +
                "public interface " + name + "Mapper extends BaseMapper<" + name + "> {\n" +
                "\n" +
                "}";
        String fileName = name + "Mapper.java";
        String fold = "dao";
        writeToFile(content, fold, fileName);
        //创建xml文件
        fileName = getMapperPath() + name + "Mapper.xml";
        content = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >\n" +
                "<mapper namespace=\"" + packageName + ".dao." + name + "Mapper\" >\n" +
                " \n" +
                "</mapper>";
        writeXmlFile(content, fileName);
    }


    //获取所有字段   0获取model 1获取listPar  2获取addPar  3获取result
    private FileContent getAllCol() {
        FileContent fileContent = new FileContent();
        boolean importDate = false;
        try {
            List<Entity> entityList = Db.use().query("select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT from information_schema.COLUMNS where table_name = '" + StrUtil.toUnderlineCase(autoCodePar.getMainName()) + "' and table_schema ='" + autoCodePar.getDbName() + "'");
            for (int i = 0; i < entityList.size(); i++) {
                Entity entity = entityList.get(i);
                String name = StrUtil.toCamelCase(entity.get("COLUMN_NAME").toString());
                String type = entity.get("DATA_TYPE").toString();
                String comment = entity.get("COLUMN_COMMENT").toString();
                String result = "";
                switch (type) {
                    case "int":
                        result = "Integer ";
                        break;
                    case "text":
                    case "varchar":
                        result = "String ";
                        break;
                    case "double":
                    case "decimal":
                        result = "Double ";
                        break;
                    case "datetime":
                    case "date":
                        if (!importDate) {
                            fileContent.getImportString().append("import java.util.Date;\n" +
                                    "import com.fasterxml.jackson.annotation.JsonFormat;\n");
                            importDate = true;
                        }
                        result = "Date ";
                        break;
                }
                // 生成model
                if (result.equals("Date ")) {
                    fileContent.getContentString().append("   @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n");
                }
                if (name.equals("id")) {
                    fileContent.getContentString().append("   @TableId(value = \"id\", type = IdType.AUTO)\n");
                }
                //生成swagger注解
                String swaggerString="   @ApiModelProperty(value=\""+comment+"\",dataType = \""+result+"\",example = \"\")\n";
                String newResult = "   private " + result + name + ";\n";
                fileContent.getContentString().append(swaggerString);
                fileContent.getContentString().append(newResult);
                // 生成listPar
                StringBuilder parListString = fileContent.getParListString();
                if (!result.equals("Date ") && !name.equals("id")) {
                    newResult = "   private " + result + name + ";\n";
                    parListString.append(swaggerString);
                    parListString.append(newResult);
                }

                //  生成addPar
                StringBuilder addParString = fileContent.getAddParString();
                if (!name.equals("id")) {
                    addParString.append("   @NotBlank(message = \"" + comment + "不能为空\")\n");
                }
                if (result.equals("Date ")) {
                    newResult = "   private String " + name + ";\n";
                } else {
                    newResult = "   private " + result + name + ";\n";
                }
                addParString.append(swaggerString);
                addParString.append(newResult);

                // }if(coltype==3){
                getResultString(fileContent, name, result);

                getListFileString(fileContent, name, result, comment, i);
                getAddInitString(fileContent, name, result, comment, i);
                getSearchTjString(fileContent, name, result, comment);
                getAddFileString(fileContent, name, result, comment);
                // getResultString(fileContent, name, result);

                fileContent.getNameList().add(name);


            }
            return fileContent;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void getResultString(FileContent fileContent, String name, String result) {
        String newResult;
        StringBuilder resultString = fileContent.getResultString();
        if (result.equals("Date ")) {
            resultString.append("   @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n");
        }
        newResult = "   private " + result + name + ";\n";
        resultString.append(newResult);
        //  }

        if (!result.equals("Date ") && !name.equals("id")) {
            StringBuilder judgeString = fileContent.getJudgeString();
            judgeString.append("        if(!IsNull.isNullOrEmpty(" + mainName + "ListPar.get" + StrUtil.upperFirst(name) + "())){\n" +
                    "            queryWrapper.like(\"" + name + "\"," + mainName + "ListPar.get" + StrUtil.upperFirst(name) + "());\n" +
                    "        }\n");
        }
    }

    private void getListFileString(FileContent fileContent, String name, String result, String comment, int position) {
        StringBuilder listFileString = fileContent.getListFileString();
        if (!result.equals("Date ")) {
            listFileString.append("                ");
            if (position > 0) {
                listFileString.append(",");
            }
            listFileString.append("{field: '" + name + "', title: '" + comment + "'}\n");
        }
    }

    private void getAddInitString(FileContent fileContent, String name, String result, String comment, int position) {
        StringBuilder listFileString = fileContent.getAddInitString();
        if (!result.equals("Date ")) {
            listFileString.append("                    ");
            if (position > 0) {
                listFileString.append(",");
            }
            listFileString.append("\"" + name + "\": parent_json." + name + "\n");
        }
    }

    private void getSearchTjString(FileContent fileContent, String name, String result, String comment) {
        StringBuilder searchTjString = fileContent.getSearchTjString();
        if (!result.equals("Date ")&&!name.equals("id")) {
            String type = "text";
            if (result.equals("Boolean") || result.equals("Integer")) {
                type = "number";
            }

            searchTjString.append("            <div class=\"layui-inline layui-show-xs-block\">\n" +
                    "                <input type=\"" + type + "\" name=\"" + name + "\" placeholder=\"请输入" + comment + "\" autocomplete=\"off\" class=\"layui-input\">\n" +
                    "            </div>");
        }
    }

    private void getAddFileString(FileContent fileContent, String name, String result, String comment) {
        StringBuilder addFileString = fileContent.getAddFileString();
        if (!result.equals("Date ")&&!name.equals("id")) {
            String type = "text";
            if (result.equals("Boolean") || result.equals("Integer")) {
                type = "number";
            }
            addFileString.append(" <div class=\"layui-form-item\">\n" +
                    "        <label class=\"layui-form-label\">" + comment + "</label>\n" +
                    "        <div class=\"layui-input-block\">\n" +
                    "            <input type=\"" + type + "\" id=\"" + name + "\" name=\"" + name + "\"\n" +
                    "                   class=\"layui-input\" placeholder=\"请输入" + comment + "\">\n" +
                    "        </div>\n" +
                    "    </div>");
        }
    }

    //生成Service接口类
    private void generateInterface(FileContent fileContent) {
        // String fileName = firstUp(autoCodePar.getMainName()) + "Service.java";
        // String content=getFileContent("service",fileName);
        String packageName = getPackageName();
        StrBuilder contentString = new StrBuilder("package " + getPackageName() + ".service; \n\n\n" +
                "import com.baomidou.mybatisplus.extension.service.IService;\n" +
                "import " + packageName + ".par.ht.*;\n" +
                "import " + getPackageName() + ".result.ht.TableResultData;\n" +
                "import " + getPackageName() + ".util.AppResultData;\n" +
                "import java.util.List;\n" +
                "import " + getPackageName() + ".model." + name + ";\n");
        contentString.append("\n\n");
        contentString.append("public interface " + name + "Service extends IService<" + name + ">{\n" +
                "\n" +
                "    TableResultData " + mainName + "List(" + name + "ListPar " + mainName + "ListPar);\n" +
                "    AppResultData " + mainName + "Add(" + name + "AddPar " + mainName + "addPar);\n" +
                "    AppResultData " + mainName + "Del(Integer id);\n" +
                "}");

        writeToFile(contentString.toString(), "service", name + "Service.java");
        contentString.reset();
        contentString.append("package " + getPackageName() + ".service.impl; \n\n\n" +
                "import com.baomidou.mybatisplus.extension.service.IService;\n" +
                "import " + packageName + ".par.ht.*;\n" +
                "import " + getPackageName() + ".result.ht.TableResultData;\n" +
                "import " + getPackageName() + ".util.AppResultData;\n" +
                "import java.util.Date;\n" +
                "import java.util.List;\n" +
                "import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\n" +
                "import " + getPackageName() + ".dao." + name + "Mapper;\n" +
                "import " + getPackageName() + ".model." + name + ";\n" +
                "import " + getPackageName() + ".service." + name + "Service;\n" +
                "import java.util.ArrayList;\n" +
                "import " + getPackageName() + ".util.IsNull;\n" +
                "import org.springframework.beans.BeanUtils;\n" +
                "import org.springframework.beans.factory.annotation.Autowired;\n" +
                "import com.baomidou.mybatisplus.core.metadata.IPage;\n" +
                "import com.baomidou.mybatisplus.extension.plugins.pagination.Page;\n" +
                "import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;\n" +
                "import org.springframework.stereotype.Service;\n" +
                "import " + getPackageName() + ".result.ht." + name + "Result;");
        contentString.append("\n\n");
        contentString.append("@Service\npublic class " + name + "ServiceImpl extends ServiceImpl<" + name + "Mapper, " + name + "> implements " + name + "Service{\n" +
                "@Autowired\n" +
                "    " + name + "Mapper " + mainName + "Mapper;\n" +
                "\n" +
                "    @Override\n" +
                "    public TableResultData " + mainName + "List(" + name + "ListPar " + mainName + "ListPar) {\n" +
                "        IPage<" + name + "> page = new Page<>(" + mainName + "ListPar.getPage(), " + mainName + "ListPar.getPageSize());\n" +
                "        QueryWrapper<" + name + "> queryWrapper = new QueryWrapper<>();\n" + fileContent.getJudgeString() +
                "        page = " + mainName + "Mapper.selectPage(page, queryWrapper);\n" +
                "        List<" + name + "Result> resultList = new ArrayList<>();\n" +
                "        for (" + name + " " + mainName + " : page.getRecords()) {\n" +
                "            " + name + "Result " + mainName + "Result = new " + name + "Result();\n" +
                "            BeanUtils.copyProperties(" + mainName + ", " + mainName + "Result);\n" +
                "            resultList.add(" + mainName + "Result);\n" +
                "        }\n" +
                "        return TableResultData.success(page.getTotal(), resultList);\n" +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public AppResultData " + mainName + "Add(" + name + "AddPar " + mainName + "addPar) {\n" +
                "        " + name + " " + mainName + " = new " + name + "();\n" +
                "        BeanUtils.copyProperties(" + mainName + "addPar, " + mainName + ");\n" +
                "        if (IsNull.isNullOrEmpty(" + mainName + ".getId())) {\n");
        if (fileContent.getNameList().contains("createTime")) {
            contentString.append("            " + mainName + ".setCreateTime(new Date());\n");
        }
        contentString.append("            " + mainName + "Mapper.insert(" + mainName + ");\n" +
                "        } else {\n");
        if (fileContent.getNameList().contains("updateTime")) {
            contentString.append("            " + mainName + ".setUpdateTime(new Date());\n");
        }
        contentString.append("            " + mainName + "Mapper.updateById(" + mainName + ");\n" +
                "        }\n" +
                "        return AppResultData.successMessage(\"成功\");\n" +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public AppResultData " + mainName + "Del(Integer id) {\n" +
                "        int count = " + mainName + "Mapper.deleteById(id);\n" +
                "        if (count > 0)\n" +
                "            return AppResultData.successMessage(\"成功\");\n" +
                "        else {\n" +
                "            return AppResultData.errorMessage(\"当前记录不存在\");\n" +
                "        }\n" +
                "    }" +
                "}");
        writeToFile(contentString.toString(), "service/impl", name + "ServiceImpl.java");

    }


    private void createListFile(FileContent fileContent) {

    }


    //获取文件的内容，如果文件不存在，则创建文件
    private String getFileContent(String fold, String fileName) {
        String filePath = autoCodePar.getPath() + fold + "/" + fileName;
        boolean exist = FileUtil.exist(filePath);
        if (exist) {
            FileReader fileReader = new FileReader(filePath);
            return fileReader.readString();
        } else {
            FileUtil.touch(filePath);
            return "";
        }
    }

    private void writeToFile(String content, String fold, String fileName) {
        String filePath = autoCodePar.getPath() + fold + "/" + fileName;
        log.error(filePath);
        FileUtil.writeString(content, filePath, "utf-8");
    }

    private void writeXmlFile(String content, String path) {
        FileUtil.writeString(content, path, "utf-8");
    }


    private String getPackageName() {
        String[] names = getClass().getPackage().getName().split("\\.");
        String name = "";
        for (int i = 0; i < names.length - 1; i++) {
            name += names[i] + ".";
        }
        return name.substring(0, name.length() - 1);
    }

    private String getResourcesPath() {
        String[] packages = getClass().getResource("/mapper").getPath().split("\\/");
        String names = "";
        for (int i = 1; i < packages.length - 1; i++) {
            if (packages[i].equals("target")) {
                packages[i] = "src/main/resources";
            }
            if (!packages[i].equals("classes"))
                names += packages[i] + "/";
        }
        return names;
    }

    private String getMapperPath() {
        return getResourcesPath() + "mapper/";
    }


    private void createController() {
        String content = getFileContent("controller", autoCodePar.getControllerName());
        String importString = "";
        String firstString = "";
        //引入service模块
        String autoString = "";

        String lastString = "";

        if (content.length() > 0) {
            int importIndex = content.indexOf("@Controller");
            importString = content.substring(0, importIndex);
            int firstIndex = content.indexOf("@Autowired");
            firstString = content.substring(importIndex, firstIndex);
            int autoIndex = content.indexOf("@PostMapping");
            autoString = content.substring(firstIndex, autoIndex);
            lastString = content.substring(autoIndex, content.length() - 1);
            log.error(autoString);
        } else {
             String controllerName=autoCodePar.getControllerName().split("\\.")[0];
            importString = "package " + getPackageName() + ".controller;\n" +
                    "\n" +
                    "import " + getPackageName() + ".par.ht." + name + "AddPar;\n" +
                    "import " + getPackageName() + ".par.ht." + name + "ListPar;\n" +
                    "import " + getPackageName() + ".result.ht.TableResultData;\n" +
                    "import " + getPackageName() + ".service." + name + "Service;\n" +
                    "import " + getPackageName() + ".util.AppResultData;\n" +
                    "import org.springframework.beans.factory.annotation.Autowired;\n" +
                    "import org.springframework.stereotype.Controller;\n" +
                    "import org.springframework.web.bind.annotation.PostMapping;\n" +
                    "import org.springframework.web.bind.annotation.GetMapping;\n" +
                    "import org.springframework.web.bind.annotation.RequestMapping;\n" +
                    "import org.springframework.web.bind.annotation.ResponseBody;\n" +
                    "import io.swagger.annotations.Api;\n" +
                    "import io.swagger.annotations.ApiOperation;\n" +
                    "import com.dhcy.jzfw.result.ht."+name+"Result;\n";
            firstString = "@Controller\n" +
                    "@RequestMapping(\"" + autoCodePar.getControllerPre() + "\")\n" +
                    "@Api(value = \""+autoCodePar.getDesc()+"\", tags = \""+autoCodePar.getControllerPre()+"\")\n" +
                    "public class " + controllerName + " {\n";
        }

        importString += "import " + getPackageName() + ".service." + name + "Service;\n";
        autoString += "\n    @Autowired\n" +
                "    " + name + "Service " + mainName + "Service;\n";
        lastString += "    @GetMapping(\"" + mainName + "List.json\")\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value=\""+autoCodePar.getDesc()+"列表\", notes=\""+autoCodePar.getDesc()+"列表\", httpMethod = \"POST\", response = "+name+"Result.class, produces = \"application/json\")\n" +
                "    TableResultData " + mainName + "List(" + name + "ListPar " + mainName + "ListPar){\n" +
                "        return  " + mainName + "Service." + mainName + "List(" + mainName + "ListPar);\n" +
                "    }\n\n" +
                "    @PostMapping(\"" + mainName + "Add.json\")\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value=\"添加修改"+autoCodePar.getDesc()+"\", notes=\"添加修改"+autoCodePar.getDesc()+"\", httpMethod = \"POST\",  produces = \"application/json\")" +
                "    AppResultData " + mainName + "Add(" + name + "AddPar " + mainName + "addPar){\n" +
                "        return " + mainName + "Service." + mainName + "Add(" + mainName + "addPar);\n" +
                "    }\n" +
                "\n" +
                "    @PostMapping(\"" + mainName + "Del.json\")\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value=\"删除"+autoCodePar.getDesc()+"\", notes=\"删除"+autoCodePar.getDesc()+"\", httpMethod = \"POST\",  produces = \"application/json\")" +
                "    AppResultData " + mainName + "Del(Integer id){\n" +
                "        return  " + mainName + "Service." + mainName + "Del(id);\n" +
                "    }\n";
        String contentString = importString + firstString + autoString + lastString + " }";
       // log.error(contentString);
        writeToFile(contentString, "controller", autoCodePar.getControllerName());


    }

    @Data
    class AutoCodePar {
        String projectPath = getClass().getResource("").getPath();
        //要生成的接口名称(表名)
        String mainName = "home";

        String dbName = "jzfw";

        String controllerName = "HomeController.java";

        String controllerPre = "home";

        String htmlFold = "test";
        //房间列表实体类
        String desc="房间列表";

        private String getPath() {
            String[] packages = this.projectPath.split("\\/");
            String names = "";
            for (int i = 1; i < packages.length - 1; i++) {
                if (packages[i].equals("target")) {
                    packages[i] = "src/main/java";
                }
                if (!packages[i].equals("classes"))
                    names += packages[i] + "/";
            }
            return names;
        }
    }


    @Data
    static class FileContent {
        StringBuilder importString = new StringBuilder();
        StringBuilder startString = new StringBuilder();
        StringBuilder contentString = new StringBuilder();
        StringBuilder parListString = new StringBuilder();
        StringBuilder addParString = new StringBuilder();
        StringBuilder resultString = new StringBuilder();
        StringBuilder endString = new StringBuilder();
        StringBuilder judgeString = new StringBuilder();
        List<String> nameList = new ArrayList<>();
        //表格列表字段
        StringBuilder listFileString = new StringBuilder();
        //搜索条件
        StringBuilder searchTjString = new StringBuilder();
        //增加修改页面表单
        StringBuilder addFileString = new StringBuilder();

        StringBuilder addInitString = new StringBuilder();
    }

}
